import {
	isBoolean,
	url2String
} from "@/common/util.js";
import {
	userMsg,
	platformAuth,
	userStatus
} from "@/http/api.js";
import Cache from "@/common/Cache.js";
const config = Symbol("config");
const isCompleteURL = Symbol("isCompleteURL");
const requestBefore = Symbol("requestBefore");
const requestAfter = Symbol("requestAfter");
// 无需验证token接口列表
const unloginInterfaceList = [userMsg, platformAuth, userStatus];

class Request {
	constructor(arg) {
		uni.getNetworkType({
			success: res => {
				this.isConnected = res.networkType === "none" ? false : true;
			}
		});
		uni.onNetworkStatusChange(res => {
			this.isConnected = res.isConnected;
			if (!this.isConnected) {
				uni.showToast({
					title: "未连接到网络~",
					icon: "none"
				});
			}
		});
		this[config] = {
			header: {
				"content-type": "application/json",
				"x-zdsoft-agent": "mobile",
				// #ifndef H5
				"Accept-Language": 'zh-CN'
				// #endif
			},
			method: "GET",
			dataType: "json",
			loading: false,
			mask: true,
			title: "加载中",
			failToast: false
		}
	}

	static[requestBefore](config) {
		if (Cache.has("_token")) {
			config.header.Authorization = `Bearer ${Cache.get("_token")}`;
		} else {
			if (!unloginInterfaceList.some(path => config.url.includes(path))) {
				return;
			}
		}
		return config;
	}

	static[requestAfter](response) {
		return response;
	}

	static[isCompleteURL](url) {
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
	}

	mergeOptions(_options) {
		let options = {
			...this[config],
			..._options
		};
		options.url = Request[isCompleteURL](options.url) ?
			options.url : options.url;
		options.data = options.data || {};
		options.cache =
			options.method === "GET" ?
			isBoolean(options.cache) ?
			options.cache :
			true :
			false;
		options = {
			...options,
			...Request[requestBefore](options)
		};
		return options;
	}

	then(options) {
		const cacheName = url2String(options.url, options.data, "_");
		return new Promise((resolve, reject) => {
			// if (!this.isConnected) {
			// 	reject("未连接网络");
			// 	return;
			// }
			if (options.loading) uni.showLoading({
				title: options.title,
				mask: options.mask
			});
			options.success = res => {
				const {
					data,
					statusCode,
					errMsg
				} = res;
				if (statusCode !== 200) {
					if(options.failToast){
						uni.showToast({
							title: data.message,
							icon: "none"
						});	
					}
					reject();
					return;
				}

				Cache.set("unLogin", false);

				// 获取token 特殊格式处理
				if (data.access_token) {
					var content = data
				} else {
					var content = data.data
					var msg = data.message
					var code = data.code
				}
				console.log('msg',msg,code)

				if (code && code !== 200) {
					switch (code) {
						case 401:
							Cache.delete("_token");
							Cache.set("unLogin", true);
							uni.reLaunch({
								url: "/pages/tabBar/index/indexNew"
							});
							console.log('失效')
							// uni.showToast({
							// 	title: "登录失效，请重新登录~",
							// 	icon: "none"
							// });
							break;
						case 404:
							Cache.set("unLogin", false);
							Cache.delete("_token");
							uni.reLaunch({
								url: "/pages/tabBar/index/indexNew"
							});
							break;
						default:
							if(options.failToast){
								uni.showToast({
									title: msg,
									icon: "none"
								});	
							}
							reject(msg);
							break;
					}
					return;
				}

				let response = Request[requestAfter](content);
				if (options.cache) {
					Cache.set(cacheName, response, 0);
				}
				resolve(Request[requestAfter](content));
			};
			options.fail = err => {
				uni.showToast({
					title: "请求失败，请稍后再试~",
					icon: "none"
				});
				reject(err);
			};
			options.complete = () => {
				if (options.loading) uni.hideLoading();
			}
			uni.request(options);
		});
	}

	fetch = (options = {}) => {
		options = this.mergeOptions(options);
		let response = {};
		response = this.then(options);
		return response;
	};
	install(Vue) {
		Vue.prototype.$request = this.fetch;
	}
}


export default new Request();
